package com.heather.exam.controller.bank;

import com.alibaba.fastjson.JSONArray;
import com.heather.exam.pojo.Result;
import com.heather.exam.pojo.table.Options;
import com.heather.exam.pojo.table.Question;
import com.heather.exam.pojo.vo.QuestionItemVO;
import com.heather.exam.pojo.vo.QuestionVO;
import com.heather.exam.service.QuestionService;
import com.heather.exam.until.ExcelUtils;
import com.heather.exam.until.JwtUtils;
import com.heather.exam.until.StingUtilHkj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

@RestController
public class BankController {
    @Autowired
    QuestionService questionService;
    //EXCEL文件导入
    @PostMapping("/api/question_bank/up_question")
    public Result handleQuestionImport(@RequestPart("file") MultipartFile file,
                                        @RequestPart("question_bank_id") String bankId) throws Exception {
        // 提取文件信息
        JSONArray jsonArrayFromFile = extractDataFromFile(file);

        // 读取并转换Excel数据为QuestionVO对象列表
        List<QuestionVO> questions = convertExcelToQuestionVOs(file, QuestionVO.class);

        // 处理每个问题的选项
        List<QuestionVO> questionVOS = processQuestionOptions(questions);

        //添加题目和选项到数据库，再把题目归纳到题库
        return saveQuetionAndOptionsAndAddBank(questionVOS, bankId);
    }

    @PostMapping("/api/question_bank/upload")
    public Result alongAddQuesion(@RequestBody QuestionItemVO questionVO){
        String questionBankid = questionVO.getQuestionBankid();
        List<Options> options = questionVO.getOptions();
        Question question = new Question();
        question.setImage(questionVO.getImage());
        question.setContent(questionVO.getContent());;
        Question question1 = checkType(questionVO.getType(), question);

        boolean b = questionService.addQuestion(question1, options, questionBankid);
        if (b) {
            return Result.success(questionVO);
        }
        return Result.error(String.valueOf(questionVO));
    }
    @GetMapping("/api/question_bank/share_bank")
    public Result share(@RequestParam("question_bank_id") String questionBankid,@RequestParam("state")String state,@RequestParam("token")String token){
        Integer role = (Integer) JwtUtils.parseJWT(token).get("user_role");
        Integer userId = (Integer) JwtUtils.parseJWT(token).get("user_id");
        if (role==1){
            return Result.error("您没有权限");
        }
        int check = questionService.check(questionBankid);
        if (check!=userId){
            return Result.error("该题库不属于你");
        }
        questionService.updateShare(questionBankid,state);
        return Result.success("状态修改成功");
    }

    private JSONArray extractDataFromFile(MultipartFile file) throws Exception {
        JSONArray array = ExcelUtils.readMultipartFile(file);
        System.out.println("导入数据为:" + array);
        return array;
    }

    private List<QuestionVO> convertExcelToQuestionVOs(MultipartFile file, Class<QuestionVO> clazz) throws Exception {
        return ExcelUtils.readMultipartFile(file, clazz);
    }

    private List<QuestionVO> processQuestionOptions(List<QuestionVO> questions) {
        for (QuestionVO question : questions) {
            // 获取选项
            String options = question.getOptions();

            // 处理单个单元格内的选项
            List<Options> optionsList = StingUtilHkj.parseData(options);

            System.out.println(optionsList.toArray().length);
            for (Options option : optionsList) {
                question.setOption(option);//封装选项
                System.out.println(question.getOption().getContent() + " - Correct: " + question.getOption().getIsCorrect());
            }

            // 输出问题对象的信息
            System.out.println(question.toString());
        }
        return questions;
    }

    private Question checkType(String type, Question question) {
        if (type.equals("判断")){
            question.setType(1);
        }
        if (type.equals("选择")){
            question.setType(2);
        }
        if (type.equals("填空")){
            question.setType(3);
        }
        if (type.equals("简答")){
            question.setType(4);
        }
        return question;
    }

    private Result saveQuetionAndOptionsAndAddBank(List<QuestionVO> questions, String bankId){
        boolean lastResult = false;
        for (QuestionVO questionVO : questions) {
            Question question = new Question();
            question.setContent(questionVO.getContent());
            String type = questionVO.getType();
            Question question1 = checkType(type, question);

            //            将List<QuestionVO>中的options转换为List<Options>
            List<Options> contentsList = extractPropertyToList(questions, QuestionVO::getOption);


            lastResult = questionService.addQuestion(question1,contentsList,bankId);
        }
        if (lastResult){
            return Result.success("添加成功");
        }else{
            return Result.error("添加失败，请检查格式是否正确");
        }
    }
    public static <T, R> List<R> extractPropertyToList(List<T> sourceList, Function<T, R> propertyExtractor) {
        List<R> result = new ArrayList<>();
        for (T obj : sourceList) {
            R value = propertyExtractor.apply(obj);
            result.add(value);
        }
        return result;
    }

}
